package org.blame.cozebyspring.service;



import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//http://127.0.0.1:8080/ai/qa?q=%E4%BB%8A%E5%A4%A9%E9%94%A6%E5%B7%9E%E7%9A%84%E5%A4%A9%E6%B0%94%E6%80%8E%E4%B9%88%E6%A0%B7




@Service
public class CozeService {

    @Value("${coze.token}")
    private String token;

    @Value("${coze.bots.answerRabbit}")
    private String qaBotId;

    @Value("${coze.bots.codeHelper}")
    private String codeBotId;

//    @Value("${coze.apps.translateApp}")
//    private String translateAppId;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // =========================
    // 构建消息内容
    // =========================
    private List<Map<String, Object>> buildMessage(String content) {
        Map<String, Object> msg = new HashMap<>();
        msg.put("role", "user");
        msg.put("content", content);
        msg.put("content_type", "text");
        return List.of(msg);
    }

    // =========================
    // 通用请求方法
    // =========================
    private String sendCozeRequest(String url, Map<String, Object> body) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setBearerAuth(token);
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 发送初始请求
            Map<String, Object> data = postForData(url, body, headers);
            if (data == null) return "返回数据格式异常";

            String conversationId = String.valueOf(data.get("conversation_id"));
            String chatId = String.valueOf(data.get("id"));
            String status = String.valueOf(data.get("status"));

            // 异步轮询等待完成
            status = pollStatus(conversationId, chatId, headers, status);

            // 获取消息列表
            List<?> messagesList = fetchMessages(conversationId, chatId, headers);

            // 解析并返回 answer
            return extractAnswer(messagesList);

        } catch (Exception e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }

    // ------------------------
    // 发送 POST 请求并返回 data Map
    // ------------------------
    private Map<String, Object> postForData(String url, Map<String, Object> body, HttpHeaders headers) {
        ResponseEntity<Map> resp = restTemplate.postForEntity(url, new HttpEntity<>(body, headers), Map.class);
        Object dataObj = resp.getBody().get("data");
        return (dataObj instanceof Map) ? (Map<String, Object>) dataObj : null;
    }

    // ------------------------
    // 异步轮询 status
    // ------------------------
    private String pollStatus(String conversationId, String chatId, HttpHeaders headers, String status) throws InterruptedException {
        int maxRetry = 20, interval = 500, count = 0;
        while (!"done".equalsIgnoreCase(status) && count < maxRetry) {
            Thread.sleep(interval);
            String retrieveUrl = "https://api.coze.cn/v3/chat/retrieve?conversation_id=" + conversationId
                    + "&chat_id=" + chatId;
            ResponseEntity<Map> retrieveResp = restTemplate.exchange(retrieveUrl, HttpMethod.GET,
                    new HttpEntity<>(headers), Map.class);
            Object retrieveDataObj = retrieveResp.getBody().get("data");
            if (retrieveDataObj instanceof Map) {
                Map<String, Object> retrieveData = (Map<String, Object>) retrieveDataObj;
                status = String.valueOf(retrieveData.get("status"));
            }
            count++;
        }
        return status;
    }

    // ------------------------
    // 获取消息列表
    // ------------------------
    private List<?> fetchMessages(String conversationId, String chatId, HttpHeaders headers) {
        String listUrl = "https://api.coze.cn/v3/chat/message/list?conversation_id=" + conversationId
                + "&chat_id=" + chatId;
        ResponseEntity<Map> listResp = restTemplate.exchange(listUrl, HttpMethod.GET, new HttpEntity<>(headers), Map.class);
        Object listDataObj = listResp.getBody().get("data");

        if (listDataObj instanceof Map listData && listData.get("messages") instanceof List messages) {
            return messages;
        } else if (listDataObj instanceof List messages) {
            return messages;
        }
        return null;
    }

    // ------------------------
    // 提取 type=answer 的消息
    // ------------------------
    private String extractAnswer(List<?> messagesList) {
        if (messagesList == null || messagesList.isEmpty()) return "消息列表为空";

        for (Object item : messagesList) {
            if (!(item instanceof Map<?, ?> msg)) continue;

            if (!"answer".equalsIgnoreCase(String.valueOf(msg.get("type")))) continue;

            Object contentObj = msg.get("content");
            if (contentObj == null) continue;

            String contentStr = String.valueOf(contentObj);

            // JSON 解析
            if (contentStr.startsWith("{")) {
                try {
                    Map<?, ?> jsonMap = objectMapper.readValue(contentStr, Map.class);
                    if (jsonMap.containsKey("msg")) return String.valueOf(jsonMap.get("msg"));
                    if (jsonMap.containsKey("data")) return String.valueOf(jsonMap.get("data"));
                } catch (Exception ignored) {}
            } else {
                return contentStr;
            }
        }

        return "未获取到回答内容";
    }

    // =========================
    // 问答机器人
    // =========================
    public String askQuestion(String question) {
        return sendCozeRequest("https://api.coze.cn/v3/chat", Map.of(
                "bot_id", qaBotId,
                "user_id", "spring_user",
                "stream", false,
                "auto_save_history", true,
                "additional_messages", buildMessage(question)
        ));
    }

    // =========================
    // 代码助手
    // =========================
    public String askCodeHelper(String question) {
        return sendCozeRequest("https://api.coze.cn/v3/chat", Map.of(
                "bot_id", codeBotId,
                "user_id", "spring_user",
                "stream", false,
                "auto_save_history", true,
                "additional_messages", buildMessage(question)
        ));
    }
//
//    // =========================
//    // 翻译助手（App）
//    // =========================
//    public String translate(String text, String lang) {
//        String content = String.format("将以下内容翻译成%s: %s", lang, text);
//        return sendCozeRequest("https://api.coze.cn/v3/chat", Map.of(
//                "app_id", translateAppId,
//                "user_id", "spring_user",
//                "stream", false,
//                "auto_save_history", true,
//                "additional_messages", buildMessage(content)
//        ));
//    }
}